package com.soulkun.smarthome.ui.main.personal

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.view.View
import androidx.databinding.ObservableField
import androidx.navigation.fragment.findNavController
import androidx.navigation.navGraphViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.maps.MapsInitializer
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.*
import com.google.android.material.snackbar.Snackbar
import com.soulkun.smarthome.R
import com.soulkun.smarthome.databinding.AppFragmentMainPersonalFamilyCreateBinding
import com.soulkun.smarthome.logic.Constant
import com.soulkun.smarthome.logic.enum.NavigationEnum
import com.soulkun.smarthome.logic.vo.RoomSelectVO
import com.soulkun.smarthome.ui.main.AppMainActivity
import com.soulkun.smarthome.ui.main.personal.adapter.AppMainPersonalFamilyCreateRoomListAdapter
import com.soulkun.smarthome.ui.main.personal.viewmodel.AppMainPersonalFamilyCreateViewModel
import soulkun.library.mvvm.component.BaseDataBindingFragment
import soulkun.library.utils.navigateSafe
import soulkun.library.utils.permission.PermissionUtils
import soulkun.library.utils.screen.ScreenUtils
import soulkun.library.utils.toast

class AppMainPersonalFamilyCreateFragment :
    BaseDataBindingFragment<AppFragmentMainPersonalFamilyCreateBinding>() {

    private lateinit var navigationEnum: NavigationEnum

    private val viewModel by navGraphViewModels<AppMainPersonalFamilyCreateViewModel>(R.id.app_navigation_family_create)

    private lateinit var geocodeSearch: GeocodeSearch

    private val adapter by lazy {
        AppMainPersonalFamilyCreateRoomListAdapter(mContext, viewModel.familyRoomList)
    }

    override fun setLayout(): Int {
        return R.layout.app_fragment_main_personal_family_create
    }

    override fun initView() {
        if (navigationEnum == NavigationEnum.Main) {
            ScreenUtils.setViewFitSystemWindows(requireDataBinding().root)
        }
        requireDataBinding().rvMainPersonalFamilyCreateRoomList.layoutManager =
            LinearLayoutManager(mContext)
        requireDataBinding().rvMainPersonalFamilyCreateRoomList.adapter = adapter
    }

    override fun initData() {
        geocodeSearch = GeocodeSearch(mContext)
        requireDataBinding().lifecycleOwner = viewLifecycleOwner
        requireDataBinding().viewModel = viewModel
        requireDataBinding().onClickListener = View.OnClickListener {
            when (it.id) {
                R.id.tv_main_personal_family_create_text_cancel -> {
                    findNavController().navigateUp()
                }
                R.id.tv_main_personal_family_create_text_save -> {
                    viewModel.createFamily().observe(viewLifecycleOwner) { result ->
                        val result = result.getOrNull()
                        result?.statusMessage?.run {
                            toast()
                            when (navigationEnum) {
                                NavigationEnum.Splash -> {
                                    AppMainActivity.startIntentAnimationSlideVertical(mActivity)
                                    mActivity.finish()
                                }
                                NavigationEnum.Main -> {
                                    findNavController().navigateUp()
                                }
                            }
                        }
                    }
                }
                R.id.view_main_personal_family_create_background_location -> {
                    if (PermissionUtils.fragmentCheckPermissionList(
                            this,
                            mContext,
                            listOf<String>(
                                Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.READ_PHONE_STATE
                            ),
                            Constant.PERMISSION_REQUEST_LOCATION
                        )
                    ) {
                        viewModel.navigationEnum = navigationEnum
                        findNavController().navigateSafe(
                            R.id.action_appMainPersonalFamilyCreateFragment3_to_appMainPersonalFamilyCreateLocationFragment,
                            R.id.appMainPersonalFamilyCreateFragment3
                        )
                    }
                }
                R.id.tv_main_personal_family_create_add_room -> {
                    viewModel.familyRoomList.add(RoomSelectVO(ObservableField("请输入房间名称")))
                }
            }
        }
    }

    override fun initListener() {
        geocodeSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
            // 经纬度转位置名称
            override fun onRegeocodeSearched(result: RegeocodeResult?, rCode: Int) {
                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (result != null && result.regeocodeAddress != null && result.regeocodeAddress.formatAddress != null) {
                        val locationText = result.regeocodeAddress.formatAddress
                        requireDataBinding().tvMainPersonalFamilyCreateTextFamilyLocation.text =
                            locationText
                    }
                }
            }

            override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
            }
        })
        viewModel.familyLocationLiveData.observe(viewLifecycleOwner) {
            geocodeSearch.getFromLocationAsyn(
                RegeocodeQuery(
                    LatLonPoint(
                        it.latitude,
                        it.longitude
                    ), 100f, GeocodeSearch.AMAP
                )
            )
        }
    }

    override fun doOnCreate() {
        navigationEnum =
            arguments?.getSerializable("navigationType") as NavigationEnum
        MapsInitializer.updatePrivacyShow(mContext, true, true)
        MapsInitializer.updatePrivacyAgree(mContext, true)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            Constant.PERMISSION_REQUEST_LOCATION -> {
                for (i in permissions.indices) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !shouldShowRequestPermissionRationale(
                                permissions[i]
                            )
                        ) { //如果用户拒接并选择不再询问
                            Snackbar.make(
                                requireDataBinding().root,
                                "请授权位置和电话权限，否则无法设置家庭位置",
                                Snackbar.LENGTH_LONG
                            )
                                .setAction(
                                    "前去设置"
                                ) { PermissionUtils.goToPermissionSettingPage(mContext) }
                                .show()
                            return
                        }
                    }
                }
                findNavController().navigateSafe(
                    R.id.action_appMainPersonalFamilyCreateFragment3_to_appMainPersonalFamilyCreateLocationFragment,
                    R.id.appMainPersonalFamilyCreateFragment3
                )
            }
        }
    }

}